#include <STC15F2K60S2.H>
#include "Delay.h"

sbit R1 = P3^0;
sbit R2 = P3^1;
sbit R3 = P3^2;
sbit R4 = P3^3;

sbit C4 = P3^4;
sbit C3 = P3^5;
sbit C2 = P4^2; 
sbit C1 = P4^4; 

unsigned char Independent_Key()
{
	unsigned char key_num = 0;
	
	if(R1 == 0){Delay20ms();while(R1 == 0);Delay20ms();key_num = 1;}
	else if(R2 == 0){Delay20ms();while(R2 == 0);Delay20ms();key_num = 2;}
	else if(R3 == 0){Delay20ms();while(R3 == 0);Delay20ms();key_num = 3;}
	else if(R4 == 0){Delay20ms();while(R4 == 0);Delay20ms();key_num = 4;}
	
	return key_num;
}


unsigned char Scan_Key()
{
	unsigned char key_num = 0;
	
	R1 = 0;
	R2 = R3 = R4 = 1;
	C1 = C2 = C3 = C4 = 1;
	if(C1 == 0){Delay20ms();while(C1 == 0);Delay20ms();key_num = 1;}
	else if(C2 == 0){Delay20ms();while(C2 == 0);Delay20ms();key_num = 2;}
	else if(C3 == 0){Delay20ms();while(C3 == 0);Delay20ms();key_num = 3;}
	else if(C4 == 0){Delay20ms();while(C4 == 0);Delay20ms();key_num = 4;}
	
	R2 = 0;
	R1 = R3 = R4 = 1;
	C1 = C2 = C3 = C4 = 1;
	if(C1 == 0){Delay20ms();while(C1 == 0);Delay20ms();key_num = 5;}
	else if(C2 == 0){Delay20ms();while(C2 == 0);Delay20ms();key_num = 6;}
	else if(C3 == 0){Delay20ms();while(C3 == 0);Delay20ms();key_num = 7;}
	else if(C4 == 0){Delay20ms();while(C4 == 0);Delay20ms();key_num = 8;}
	
	R3 = 0;
	R2 = R1 = R4 = 1;
	C1 = C2 = C3 = C4 = 1;
	if(C1 == 0){Delay20ms();while(C1 == 0);Delay20ms();key_num = 9;}
	else if(C2 == 0){Delay20ms();while(C2 == 0);Delay20ms();key_num = 10;}
	else if(C3 == 0){Delay20ms();while(C3 == 0);Delay20ms();key_num = 11;}
	else if(C4 == 0){Delay20ms();while(C4 == 0);Delay20ms();key_num = 12;}

	R4 = 0;
	R2 = R3 = R1 = 1;
	C1 = C2 = C3 = C4 = 1;
	if(C1 == 0){Delay20ms();while(C1 == 0);Delay20ms();key_num = 13;}
	else if(C2 == 0){Delay20ms();while(C2 == 0);Delay20ms();key_num = 14;}
	else if(C3 == 0){Delay20ms();while(C3 == 0);Delay20ms();key_num = 15;}
	else if(C4 == 0){Delay20ms();while(C4 == 0);Delay20ms();key_num = 16;}
	
	return key_num;
	
}


